<template>
  <el-container id="message-subscribe-list">
    <el-main>
      <el-container>
        <el-header class="header">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item>订阅消息</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <el-col :span="4">
            <router-link to="/message/subscribe/add"><el-button>新增订阅消息</el-button></router-link>
          </el-col>
        </el-header>
      </el-container>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column
          prop="scriptName"
          label="名称"
          width="150">
        </el-table-column>
        <el-table-column
          prop="delaySeconds"
          label="延时"
          width="120">
        </el-table-column>
        <el-table-column
          prop=""
          label="创建时间"
          width="160">
        <template slot-scope="scope">
          {{formatTime(scope.row.createdTime)}}
        </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="修改时间"
          width="160">
          <template slot-scope="scope">
          {{formatTime(scope.row.updatedTime)}}
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="创建人"
          width="80">
          <template slot-scope="scope">
          {{ scope.row.createdUser.nickname || scope.row.createdUser.username || '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="修改人"
          width="80">
          <template slot-scope="scope">
          {{ scope.row.updatedUser ? (scope.row.updatedUser.nickname
            || scope.row.updatedUser.username || '') : '' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="valid"
          label="状态"
          width="160">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.valid"
              @change="changeStatus(scope.row.id, scope.row.valid)"
              active-text="生效"
              inactive-text="已失效"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="140">
          <template slot-scope="scope">
            <!-- <el-button @click="toPreview(scope.row)" type="text" size="small">查看</el-button> -->
            <el-button @click="toEdit(scope.row.id || '')" type="text" size="small">编辑</el-button>
            <el-button @click="toDelete(scope.row.id || '')" type="text" size="small" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          background
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentPageChange"
          :current-page="page.page + 1"
          :page-sizes="[10, 20, 100, 300, 400]"
          :page-size="20"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalElement">
        </el-pagination>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import moment from 'moment';
import op from 'object-path';
// import axios from 'axios';
import { mapState, mapActions } from 'vuex';
import cookie from '../../../lib/cookie';

// import auth from '../../../util/auth';
import CONSTANT from '../../../constant/common';

const audioTemplate = '<audio controls><source src="{{$}}"></source></audio>';
export default {
  data() {
    return {
      userRole: cookie(CONSTANT.COOKIE_USER_ROLE),
    };
  },
  components: {
  },
  computed: {
    ...mapState({
      tableData: state => state.message.subscribeMsgList,
      page: state => state.message.subscribePage,
    }),
    appId() {
      const localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ?
        JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : {};
      return this.$store.state.woa.currentWoa.appId || localWoa.appId;
    },
  },
  mounted() {
    this.checkAppIdOk({
      appId: this.appId,
    }).then(() => {
      this.getSubscribeMessageList({ ...this.page, appid: this.appId });
    }, () => {
      this.$message.warning('当前公众号暂不可用，请稍后再试或选择其他公众号');
      this.$router.replace('/home');
    });
  },
  methods: {
    ...mapActions([
      'checkAppIdOk',
      'getSubscribeMessageList',
      'changeSubscribeMessageStatus',
      'getSubscribeMessage',
      'deleteSubscribeMessage',
      'getMpNewsByMediaId',
      'getImageByMediaId',
      'getVoiceByMediaId',
    ]),
    toPreview(item) {
      const myAlert = (content) => {
        this.$alert(content, '订阅消息预览', {
          dangerouslyUseHTMLString: true,
          // center: true,
        });
      };
      this.getSubscribeMessage({
        appid: this.appId,
        id: item.id,
      }).then((data) => {
        const { pushMessageType, pushContent } = data;
        if (pushMessageType === 'TEXT') {
          return myAlert(pushContent.replace(/(\r\n)/g, '<br>'));
        }
        if (pushMessageType === 'MPNEWS') {
          return this.getMpNewsByMediaId({
            appid: this.appId,
            mediaId: pushContent,
          }).then((info) => {
            const content = op.get(info, 'articles.0.content');
            return myAlert(content.replace('data-src', 'src'));
          });
        }
        if (pushMessageType === 'IMAGE') {
          return this.getImageByMediaId({
            appid: this.appId,
            mediaId: pushContent,
          }).then((blobData) => {
            const reader = new FileReader();
            reader.readAsDataURL(blobData);
            const myImg = new Image(320);
            reader.onload = () => {
              myImg.setAttribute('src', reader.result);
              return myAlert(myImg.outerHTML);
            };
          });
        }
        if (pushMessageType === 'VOICE') {
          return this.getVoiceByMediaId({
            appid: this.appId,
            mediaId: pushContent,
          }).then((blobData) => {
            const ret = window.URL.createObjectURL(blobData);
            const myVoice = audioTemplate.replace('{{$}}', ret);
            return myAlert(myVoice);
          });
        }
        return '';
      });
    },
    isEditable(item) {
      return item.status === 'WAITING';
    },
    isDeletable(item) {
      return item.status === 'WAITING' || item.status === 'INVALID';
    },
    changeStatus(id, nv) {
      console.log('changeStatus');
      this.changeSubscribeMessageStatus({
        appid: this.appId,
        isActive: nv,
        id,
      }).then(() => {
        this.$message({
          type: 'success',
          message: '更新状态成功',
        });
        setTimeout(() => {
          this.getSubscribeMessageList({ ...this.page, appid: this.appId });
        }, 2000);
      }, (e) => {
        this.$message({
          type: 'error',
          message: `更新状态失败->${e.message}`,
        });
      });
    },
    getMessageStatus(status) {
      return status ? '生效' : '已失效';
    },
    handlePageSizeChange(val) {
      this.getSubscribeMessageList({ ...this.page, size: val, appid: this.appId });
    },
    handleCurrentPageChange(val) {
      this.getSubscribeMessageList({ ...this.page, page: (val - 1), appid: this.appId });
    },
    formatTime(stamp) {
      return stamp ? moment(stamp).format('YYYY-MM-DD HH:mm:ss') : '--';
    },
    toDelete(id) {
      this.deleteSubscribeMessage({
        id,
        appid: this.appId,
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功',
        });
        setTimeout(() => {
          this.getSubscribeMessageList({ ...this.page, appid: this.appId });
        }, 2000);
      }, (e) => {
        this.$message({
          type: 'error',
          message: `删除失败->${e.message}`,
        });
      });
    },
    toEdit(id) {
      this.$router.push({
        path: `/message/subscribe/edit/${id}`,
      });
    },
  },
};
</script>

<style lang="less" scoped>
#message-subscribe-list {
  font-family: Helvetica, sans-serif;
  width: 100%;
  height: 100%;
  position: relative;
  .header {
    display: flex;
    justify-content: space-between;
    .breadcrumb {
      height: 40px;
    }
  }
  .page {
    position: absolute;
    bottom: -20px;
    right: 20px;
  }
}
</style>

